package com.youkeda.yikao.web.config;

import com.youkeda.yikao.web.dataobject.ZhangyankunSpringUser;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：xiong
 * @date ：Created in 2019/9/1 14:55
 * @description：拦截器
 * @modified By：
 */
@Component
public class AuthHanderInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //判读方法对象是不是HandlerMethod,是进行强制转换
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod= (HandlerMethod) handler;
            //判断方法对象上有没有添加的@NeedLogin这个注解
            NeedLogin needLogin=handlerMethod.getMethodAnnotation(NeedLogin.class);
            if (needLogin!=null){
                //判断需要登录，获取登录对象,user对应的是设置时的SetSession的对象
                ZhangyankunSpringUser user= (ZhangyankunSpringUser) request.getSession().getAttribute("user");
                if (user==null){
                    //如果未获取到user登录用户，返回登录页面
                    response.sendRedirect("login.html");
                    return false;
                }
            }
        }
        return true;
    }
}
